package com.jjb.spider.mqtt.handler;

import com.jjb.spider.mqtt.cache.NodeChannelHandlerContextCache;
import com.jjb.spider.mqtt.ctx.MqttChannelHandlerContext;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ChannelHandler.Sharable
public class MqttNetHandler extends ChannelInboundHandlerAdapter {

    private final Logger log =  LoggerFactory.getLogger(this.getClass());

    private final MqttHandler mqttHandler;

    public MqttNetHandler(MqttHandler mqttHandler) {
        this.mqttHandler = mqttHandler;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if( msg == null ) {
            return;
        }

        if( msg instanceof MqttMessage) {
            this.mqttHandler.mqttHandler(ctx, (MqttMessage) msg);
        } else if ( msg instanceof IdleStateEvent) {
            this.mqttHandler.connectionTimeoutHandler(ctx, (IdleStateEvent)msg);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        this.mqttHandler.closeChannelHandlerContext(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接成功:{},",ctx.channel().remoteAddress().toString());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //this.mqttHandler.closeChannelHandlerContext(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("连接发生异常:" + cause.getMessage(), cause);
       ctx.close();
    }
}
